#include <avr/io.h>
#include <avr/interrupt.h>
#include "global.h"
#include "rf02.h"

#define F_CPU 10000000UL
#include <util/delay.h>

#define RF_PORT	PORTB
#define RF_DDR	DDRB
#define RF_PIN	PINB

#define SDI		0	// SDI,  -> RF02
#define SCK		1	// SCK,  -> RF02
#define CS		2	// nSEL, -> RF02
#define IRQ		4	// nIRQ, <- RF02

// FSK: Pullup oder Pulldown

void rf02_trans(unsigned short wert)
{	unsigned char i;

	cbi(RF_PORT, CS);
	for (i=0; i<16; i++)
	{	if (wert&32768)
			sbi(RF_PORT, SDI);
		else
			cbi(RF_PORT, SDI);
		sbi(RF_PORT, SCK);
		wert<<=1;
		_delay_us(0.3);
		cbi(RF_PORT, SCK);
	}
	sbi(RF_PORT, CS);
}

void rf02_init(void)
{
	RF_PORT=(1<<CS);
	RF_DDR=(1<<SDI)|(1<<SCK)|(1<<CS);

	for (unsigned char i=0; i<15; i++)
		_delay_ms(10);			// wait until POR done
	rf02_trans(0xC0E0);			// power settings
	rf02_trans(0x8F80);
	rf02_trans(0xC2A0);			// enable tx sync bit, disable low bat detector
}

void rf02_setmodfreq(unsigned char bandwidth)
{
	rf02_trans(0x8F80|(bandwidth&7));
}

void rf02_setfreq(unsigned short freq)
{	if (freq<96)				// 430,2400MHz
		freq=96;
	else if (freq>3903)			// 439,7575MHz
		freq=3903;
	rf02_trans(0xA000|freq);
}

void rf02_setpower(unsigned char power)
{
	rf02_trans(0xB000|((power&7)<<8));
}

void rf02_setbaud(unsigned short baud)
{
	if (baud<1345)
		baud=1345;
	if (baud<19000)
		rf02_trans(0xD240);		// 25% PLL current
	else if (baud<37000)
		rf02_trans(0xD2C0);		// 33% PLL current
	else
		rf02_trans(0xD200);		// 50% PLL current
	rf02_trans(0xC800|((344828UL/baud)-1));	// Baudrate= 344827,59/(R+1)
}

void rf02_txdata(unsigned char *data, unsigned char number)
{	unsigned char i,j,wert;
	wert=0xC6;
	cbi(RF_PORT, CS);
	for (i=0; i<8; i++)
	{	if (wert&128)
			sbi(RF_PORT, SDI);
		else
			cbi(RF_PORT, SDI);
		sbi(RF_PORT, SCK);
		wert<<=1;
		_delay_us(0.2);
		cbi(RF_PORT, SCK);
	}
		rf02_shiftout(0xAA);
		rf02_shiftout(0xAA);
		rf02_shiftout(0xAA);
		rf02_shiftout(0x2D);
		rf02_shiftout(0xD4);
	for (i=0; i<number; i++)
		rf02_shiftout(*data++);
	sbi(RF_PORT, CS);
	while(RF_PIN&(1<<IRQ));		// wait until transfer done
	rf02_trans(0xC464);			// TX off after 10us
}

void rf02_shiftout(unsigned char wert)
{	unsigned char j;
	for (j=0; j<8; j++)
	{	while(RF_PIN&(1<<IRQ));
    	while(!(RF_PIN&(1<<IRQ)));
		if (wert&128)
    		sbi(RF_PORT, SDI);
    	else
    		cbi(RF_PORT, SDI);
    	wert<<=1;
    }
}

